//
//  Moya+ObjectMapper.swift
//  BaseProj
//
//  Created by 陈宇 on 2017/4/27.
//  Copyright © 2017年 科匠武汉. All rights reserved.
//

import Moya
import RxSwift
import ObjectMapper

extension ObservableType where E == Moya.Response {
    
    func unWrapper(tipError: Bool = true, error: ((_ code: Int) -> Void)? = nil) -> Observable<Any> {
        return retry(3).filterSuccessfulStatusCodes().mapJSON().map({ raw in
            guard let json = raw as? [String: Any] else {
                return [:]
            }
            return json
        }).do(onNext: { (json) in
            guard let code = json["code"] as? Int, code != 0, let msg = json["message"] as? String, !msg.isEmpty else { return }
            if let handler = error { handler(code) }
            if tipError { UIApplication.whisper(title: msg, duration: 3) }
        }, onError: { error in
            log.error(error)
            let msg = error.localizedDescription
            if tipError && !msg.isEmpty { UIApplication.whisper(title: "ERROR: " + msg, state: .error) }
        }).filter({ (json) -> Bool in
            guard let code = json["code"] as? Int else { return false }
            return code == 0
        }).map({ (json: [String : Any]) in
            guard let data = json["data"] else { return json }
            return data
        })
    }
    
}

extension ObservableType where E == Any {
    func mapObject<T: Mappable>(type: T.Type) -> Observable<T?> {
        return map { json in
            return Mapper<T>().map(JSONObject: json)
        }
    }
    
    func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> {
        return map { json in
            return Mapper<T>().mapArray(JSONObject: json) ?? []
        }
    }
}
